//
//  ZSComposeView.swift
//  ZSWeibo
//
//  Created by zsj1992 on 16/4/15.
//  Copyright © 2016年 ichange. All rights reserved.
//

import UIKit

class ZSComposeView: UIView {
    
    
    
    //声明一个保存按钮的数组
    var btns : [ZSButton]? = [ZSButton]()
    
    var target:UIViewController? = UIViewController()
    
    //定义一个数组用于保存要加载的按钮的模型
    var composeItems:[ZSComposeItem]? = {
        
        var array:[ZSComposeItem]
        
        var arrayTemp = [ZSComposeItem]()
        
        //拿到plist文件的路径
        let path = NSBundle.mainBundle().pathForResource("Compose.plist", ofType: nil)
        
        //拿到字典数组
        let dicArray = NSArray(contentsOfFile: path!) as! [[String:String]]
        
        for dic in dicArray{
            //根据字典得到模型
            let item = ZSComposeItem(dic:dic)
            arrayTemp.append(item)
        }
        
        array = arrayTemp
        
        return array
    }()
    
    
    
    
    /*懒加载子控件*/
    private lazy var ImageBGView : UIImageView = {
        let bgView = UIImageView()
        bgView.image = UIImage.snapshotScreen().applyLightEffect()
        
        return bgView
    }()
    private lazy var sloganView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))

    
    /*暴露的添加到控制器上的方法*/
    func show(target:UIViewController){
        
        self.target = target

        target.view.addSubview(self)
        
    }
    
    
    /*重写构造方法*/
    override init(frame: CGRect) {
        
        super.init(frame:UIScreen.mainScreen().bounds)
        
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
    
    
}

/*类扩展*/
extension ZSComposeView{

    //MARK: 设置UI的操作
    func setupUI(){
        
        addSubview(ImageBGView)
        addSubview(sloganView)
        addBtns()
        
        ImageBGView.snp_makeConstraints { (make) -> Void in
            make.left.right.top.bottom.equalTo(self)
        }
        
        sloganView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX)
            make.top.equalTo(self.snp_top).offset(100)
        }
    }

    
    //MARK: 添加按钮的方法-->做了一个plist文件,通过plist文件->字典转模型,拿到一个个发布的模型-->进行按钮的添加
    func addBtns(){
        
        let W:CGFloat = 80
        let H:CGFloat = 110
        let margin:CGFloat = (screenWidth - CGFloat(3*W))/4
        //遍历模型数组
        for i in 0 ..< composeItems!.count{
            
            let btn = ZSButton()
            
            btn.composeItem = composeItems![i]
            btn.setTitleColor(UIColor.darkGrayColor(), forState: .Normal)
            
            btn.frame = CGRectMake(margin + CGFloat(i%3)*(margin+W), margin+CGFloat(i/3)*(margin+H) + screenHeight, W, H)
            
//            let rect = CGRectMake(0, 0, W, H)
//            let offsetX = (W + margin) * CGFloat(i%3) + margin
//            let offsetY = (H + margin) * CGFloat(i/3) + screenHeight
//            btn.frame = CGRectOffset(rect, offsetX, offsetY)

            
            
            //给按钮绑定相应的方法
            btn.addTarget(self, action: "btnDidClick:", forControlEvents: .TouchUpInside)

            btns?.append(btn)
            
            addSubview(btn)
            
        }
    }
    
    
    
    
    
//    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
//        
//        //执行动画  依次获取每个按钮 给按钮执行动画
//        for (index,button) in btns!.reverse().enumerate() {
//            animationWith(button, index: index)
//        }
//    }
//    
//    
//    override func willMoveToSuperview(newSuperview: UIView?) {
//        super.willMoveToSuperview(newSuperview)
//        
//        //执行动画  依次获取每个按钮 给按钮执行动画
//        for (index,button) in btns!.enumerate() {
//            animationWith(button, index: index, isUp: true)
//        }
//    }
//    
//    private func animationWith(button: ZSButton, index: Int, isUp: Bool = false) {
//        UIView.animateWithDuration(0.8, delay: Double(index) * 0.03, usingSpringWithDamping: 0.6, initialSpringVelocity: 5, options: [], animations: { () -> Void in
//            //修改按钮的中心点
//            button.center = CGPoint(x: button.center.x, y: button.center.y + (isUp ? -350 : 350))
//            }, completion: { (_) -> Void in
//                if !isUp {
//                    //向下的效果
//                    self.removeFromSuperview()
//                }
//        })
//    }

    
    
    
    
    
    
    
    //将要移到父控件中的时候 -->改变一次center
    override func willMoveToWindow(newWindow: UIWindow?) {
        
        for i in 0 ..< btns!.count{
            
            let btn = btns![i]
            
            UIView.animateWithDuration(0.25, delay:Double(i)*0.01, usingSpringWithDamping: 0.8, initialSpringVelocity: 5, options: [], animations: { () -> Void in
                
                btn.center = CGPointMake(btn.center.x, btn.center.y-350)
                
                }, completion: { (_) -> Void in
                    
            })
        }
    }

    
    
    //点击屏幕的方法-->收回按钮->到埋伏的地方去
        override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

            let newBtns:[ZSButton] = (btns?.reverse())!
    
            for i in 0 ..< newBtns.count{
    
                let btn = newBtns[i]
    
            UIView.animateWithDuration(0.25, delay: Double(i)*0.01, usingSpringWithDamping: 0.8, initialSpringVelocity: 5, options: [], animations: { () -> Void in

                self.userInteractionEnabled = false
               
                btn.center = CGPoint(x: btn.center.x, y: btn.center.y + 350)

                }, completion: { (_) -> Void in
                    
                    self.userInteractionEnabled = true
                   
                    self.removeFromSuperview()
                })
            }
        }

    
    
    
    
    
    
    
    
    
    
    
    //给按钮点击绑定的方法-->处理缩放,与位置无关
    func btnDidClick(sender:ZSButton){
        
        var scale:CGFloat = 1.0
        
        for btn in btns!{
            
            //如果是被点击的按钮
            if btn == sender{
                scale = 1.5
            }else{
                scale = 0.2
            }
           
            UIView.animateWithDuration(1.0, animations: { () -> Void in
                
                btn.transform = CGAffineTransformMakeScale(scale, scale)
                
                btn.alpha = 1.0
                
                }, completion: { (_) -> Void in
            })

          
            //点击按钮后,跳转到响应的控制器-->根据btn对应的模型的类名加载控制器
            let item : ZSComposeItem = btn.composeItem!
                    
            let className = item.target
             
            let classType = NSClassFromString(className!) as! UIViewController.Type
                    
            let vc = classType.init()
            
            let nav = UINavigationController(rootViewController: vc)
            
//            self.target?.addChildViewController(nav)
            
            self.target?.presentViewController(nav, animated: true, completion: { () -> Void in

                self.removeFromSuperview()
            
            })
        }
    }
}
